package com.ruoyi.project.sms.qcloud;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.SystemContstant;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.content.PropertyTypeEnum;
import com.ruoyi.project.sms.ISMSService;
import com.ruoyi.project.utils.MD5;
import com.ruoyi.project.utils.RedisUtils;
import com.ruoyi.project.utils.SSLClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 腾讯云短信接口
 *
 * @author Administrator
 */
@Service (value = "sms")
public class SmsServiceImpl implements ISMSService {

    private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);

    //接口地址
    @Value ("${sms.sms.url}")
    public String url;

    //用户ID
    @Value ("${sms.sms.userid}")
    public String userid;

    //用户账号名
    @Value ("${sms.sms.account}")
    public String account;

    //接口密码
    @Value ("${sms.sms.password}")
    public String password;

    //阿里云短信接口


    @Autowired
    private RedisUtils redisUtils;

    String sendTime = "";

    //扩展号，没有请留空
    String extno = "";


    public String sendSingleMsg (String mobile, String msg) throws Exception {

        return "成功";
    }

    @Override
    public String sendGroupMsg (String[] mobiles, String[] msg) throws Exception {
        //多个手机号用逗号分隔
        String mobile = StringUtils.join(mobiles, ",");
        String text = "";
        return this.sendMsg(mobile, text);

    }

    private String sendMsg (String mobile, String text) throws IOException {
        List list = new ArrayList();
        list.add(new BasicNameValuePair("action", "send"));
        list.add(new BasicNameValuePair("userid", this.userid));
        list.add(new BasicNameValuePair("account", this.account));
        list.add(new BasicNameValuePair("password", MD5.GetMD5Code(this.password)));
        list.add(new BasicNameValuePair("mobile", mobile));
        list.add(new BasicNameValuePair("content", text));
        list.add(new BasicNameValuePair("sendTime", this.sendTime));
        list.add(new BasicNameValuePair("extno", this.extno));

        CloseableHttpClient httpclient = SSLClient.createSSLClientDefault();
        HttpPost post = new HttpPost(this.url);
        post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
        HttpResponse response = httpclient.execute(post);
        HttpEntity entity = response.getEntity();
        String returnString = EntityUtils.toString(entity);
        JSONObject jsonObject = JSONObject.parseObject(returnString);
        EntityUtils.consume(entity);
        if ("Success".equals(jsonObject.get("returnstatus"))) {
            log.info("发送短信成功", jsonObject.get("message").toString());
            return jsonObject.get("message").toString();
        } else {
            return "发送失败";
        }
    }


    @Override
    public String sendCode (String mobile, Integer length) throws Exception {

        String randomCode = this.getRandomCode(length == null || length.intValue() == 0 ? 4 : length);
        String text = "【找零工】尊敬的客户您好，您当前验证码为" + randomCode;
        String result = this.sendMsg(mobile, text);

        if (!result.equals("发送失败")) {
            this.redisUtils.set(SystemContstant.CHECK_CODE + mobile, randomCode);
            this.redisUtils.expire(SystemContstant.CHECK_CODE + mobile, 60);
            return "发送成功";
        } else {
            return "发送失败";
        }
    }

    @Override
    public String sendYaoqing (String mobile, String username) throws Exception {

        String text = "太好了" + username + "，有一个任务向您发起了邀请，正在等待你的同意！ 点击查看 http://app.linglinggong.net/";
        String result = this.sendMsg(mobile, text);
        //TODO 测试关闭短信发送
        if (!result.equals("发送失败")) {
            return "发送成功";
        } else {
            return "发送失败";
        }
    }


    @Override
    public boolean checkSmsCode (String mobile, String checkCode) {
        String sysCheckCode = this.redisUtils.hget(PropertyTypeEnum.SYS.getText(), "sys_check_code")+"";
        if (sysCheckCode.equals(checkCode)) {
            this.redisUtils.del(SystemContstant.CHECK_CODE + mobile);
            return false;
        }
        //通过缓存获取手机验证码
        String code = this.redisUtils.get(SystemContstant.CHECK_CODE + mobile);
        if (StringUtils.isEmpty(code)) {
            return true;
        }
        //不相等时返回错误
        if (!code.equals(checkCode)) {
            return true;
        }
        this.redisUtils.del(SystemContstant.CHECK_CODE + mobile);
        return false;
    }

    //获取随机验证码
    @Override
    public String getRandomCode (int length) {
        StringBuffer code = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    @Override
    public String decrypt (String str) throws Exception {
        return null;
    }

    @Override
    public String sendservice (String mobile, String TemplateCode) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getMobile (String mobile) throws Exception {
        return null;
    }

    @Override
    public void sendMarketingMsg (List <String> phones, String template) {

    }

    @Override
    public void sendMsgByCode(String mobile, String code) throws Exception {

    }

    @Override
    public Boolean sendMsgByCodeResult(String mobile, String code) throws Exception {
        return null;
    }

    @Override
    public void sendMsgByParameters(String mobile, String code, String templateParam) throws Exception {
        
    }
}
